﻿using System;
using System.Collections.Generic;
using System.Text;
using NFinal.Owin;

namespace NFinal.Filter
{
    public class Compress : IResponseFilter
    {
        public NFinal.Http.CompressMode CompressMode { get; set; }
        public Compress(NFinal.Http.CompressMode compressMode=Http.CompressMode.Deflate)
        {
            this.CompressMode = compressMode;
        } 
        public bool ResponseFilter(Response response)
        {
            if (CompressMode != Http.CompressMode.None)
            {
                System.IO.Stream writeStream = null;
                System.IO.Stream compressStream = new System.IO.MemoryStream();
                response.statusCode = 200;
                if (CompressMode == NFinal.Http.CompressMode.GZip)
                {
                    writeStream = new System.IO.Compression.GZipStream(compressStream, System.IO.Compression.CompressionMode.Compress, true);
                    response.headers.Add(NFinal.Constant.HeaderContentEncoding, NFinal.Constant.HeaderContentEncodingGzip);
                }
                else if (CompressMode == NFinal.Http.CompressMode.Deflate)
                {
                    writeStream = new System.IO.Compression.DeflateStream(compressStream, System.IO.Compression.CompressionMode.Compress, true);
                    response.headers.Add(NFinal.Constant.HeaderContentEncoding, NFinal.Constant.HeaderContentEncodingDeflate);
                }
                try
                {
                    try
                    {
                        response.stream.CopyTo(writeStream);
                    }
                    catch
                    {
                        return false;
                    }
                    finally
                    {
                        response.stream.Dispose();
                    }
                    response.stream = compressStream;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    writeStream?.Dispose();
                }
            }
            return true;
        }
    }
}
